package com.haoyeteng.sxbd.modular.business.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.haoyeteng.sxbd.core.base.controller.BaseController;
import com.haoyeteng.sxbd.core.base.model.ResponseResult;
import com.haoyeteng.sxbd.core.common.annotion.Permission;
import com.haoyeteng.sxbd.core.common.constant.factory.ConstantFactory;
import com.haoyeteng.sxbd.core.common.constant.factory.PageFactory;
import com.haoyeteng.sxbd.core.constant.SxbdConstants;
import com.haoyeteng.sxbd.core.exception.SxbdException;
import com.haoyeteng.sxbd.core.util.ToolUtil;
import com.haoyeteng.sxbd.modular.business.model.Account;
import com.haoyeteng.sxbd.modular.business.model.EleFence;
import com.haoyeteng.sxbd.modular.business.model.Machine;
import com.haoyeteng.sxbd.modular.business.model.ZbzhFile;
import com.haoyeteng.sxbd.modular.business.service.*;
import com.haoyeteng.sxbd.modular.business.warpper.AccountWarpper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * 差分账号控制器
 *
 * @author haoyeteng
 * @Date 2019-05-25 14:29:04
 */
@Controller
//@RequestMapping("/account")
public class AccountController extends BaseController {

    private String PREFIX = "/business/account/";

    @Autowired
    private IAccountService accountService;
    
    @Autowired
    private IMachineService machineService;
    
    @Autowired
    private IEleFenceService eleFenceService;

    @Autowired
    private IProductService productService;

    @Autowired
    private IZbzhFileService zbzhFileService;
    
   
    
    /**
     * 跳转到rtd
     */
    @RequestMapping("/rtd")
    public String rtd() {
        return PREFIX + "rtd_account.html";
    }
    
    /**
     * 获取rtd列表
     */
    @RequestMapping(value = "/rtd/list")
    @ResponseBody
    @Permission
    public ResponseResult<Object> rtdList(String condition) {
    	ResponseResult<Object> result = new ResponseResult<Object>();
    	Page<Account> page = new PageFactory<Account>().defaultPage();
        Map<String, Object> params = new HashMap<>(16);
        params.put("condition", condition);
    	List<Map<String, Object>> accounts = accountService.selectRtdAccounts(page,params);
        result.setData(new AccountWarpper(accounts).warp());
        result.setCount(page.getTotal());
     	result.setCode(SUCCESS_TIP.getCode());
     	result.setMsg(SUCCESS_TIP.getMessage());
 		return result;
    }
    
    /**
     * 跳转到绑定标识页面
     */
    @RequestMapping("/rtd/rtd_binding/{accountId}")
    public String rtdBinding(@PathVariable Integer accountId, Model model) {
    	Map<String, Object> item = accountService.selectByAccountId(accountId);
    	model.addAttribute("item",item);
        return PREFIX + "rtd_binding.html";
    }
    
    /**
     * 绑定标识
     * @param account
     * @return
     */
    @RequestMapping(value = "/rtd/binding")
    @ResponseBody
    @Permission
    public Object rtdBinding(Account account) {
    	account.setUpdateTime(new Date());
    	account.setBindingState(1);
    	accountService.updateById(account);
        return SUCCESS_TIP;
    }
    
    
    /**
     * 跳转到rtk
     */
    @RequestMapping("/rtk")
    public String rtk() {
        return PREFIX + "rtk_account.html";
    }
    
    
    /**
     * 获取rtk列表
     */
    @RequestMapping(value = "/rtk/list")
    @ResponseBody
    @Permission
    public ResponseResult<Object> rtkList(String condition) {
    	ResponseResult<Object> result = new ResponseResult<Object>();
    	Page<Account> page = new PageFactory<Account>().defaultPage();

        Map<String, Object> params = new HashMap<>(16);
        params.put("serviceType", "RTK");
        params.put("condition", condition);
    	List<Map<String, Object>> accounts = accountService.selectRtkAccounts(page, params);
        result.setData(new AccountWarpper(accounts).warp());
        result.setCount(page.getTotal());
     	result.setCode(SUCCESS_TIP.getCode());
     	result.setMsg(SUCCESS_TIP.getMessage());
 		return result;
    }
    
    /**
     * 跳转到设备申请处理页面
     */
    @RequestMapping("/rtk/rtk_review/{accountId}")
    public String review(@PathVariable Integer accountId, Model model) {
    	Map<String, Object> item = accountService.selectByAccountId(accountId);
    	model.addAttribute("item",item);
        return PREFIX + "rtk_review.html";
    }


    /**
     * 设备申请处理
     */
    @RequestMapping(value = "/rtk/review")
    @ResponseBody
    @Permission
    public Object review(Machine machine) {
    	Account account = accountService.selectById(machine.getAccountId());
    	machine.setUpdateTime(new Date());
    	boolean flag = machineService.updateById(machine);
    	if(flag) {
    		if(machine.getApplyState() ==1) {
    			ConstantFactory.me().toSendUserMsg("USER_APPLY", "您的设备申请已通过审核！您可以正常使用服务！", account.getUserId());
    			ConstantFactory.me().toSendAdminMsg("ADMIN_BINDING", "您有新的标识需要绑定，请尽快绑定！");
    		}
    		if(machine.getApplyState() ==2) {
    			ConstantFactory.me().toSendUserMsg("USER_APPLY", "由于“"+machine.getRejectReson()+"”，您上传的设备未能通过审核，为了保证服务的正常使用，请尽快重新上传设备！",account.getUserId());
    					
    		}
    	}
        return SUCCESS_TIP;
    }

    /**
     * 跳转到绑定标识页面
     */
    @RequestMapping("/rtk/rtk_binding/{accountId}")
    public String binding(@PathVariable Integer accountId, Model model) {
    	Map<String, Object> item = accountService.selectByAccountId(accountId);
    	model.addAttribute("item",item);
        return PREFIX + "rtk_binding.html";
    }
    
    /**
     * 绑定标识
     * @param account
     * @return
     */
    @RequestMapping(value = "/rtk/binding")
    @ResponseBody
    @Permission
    public Object binding(Account account) {
    	account.setStartTime(new Date());
    	account.setUpdateTime(new Date());
    	account.setBindingState(1);
    	accountService.updateById(account);
        return SUCCESS_TIP;
    }
    

    /**
     * 差分账号详情
     */
    @RequestMapping(value = "/rtk/detail/{accountId}")
    @Permission
    public String detail(@PathVariable("accountId") Integer accountId,Model model) {
    	Map<String, Object> item = accountService.selectByAccountId(accountId);
    	item.put("applyStateName", ConstantFactory.me().getApplyStateName((Integer)item.get("applyState")));
    	item.put("bindingStateName", ConstantFactory.me().getBindingStateName((Integer)item.get("bindingState")));
    	item.put("payTimeName", ConstantFactory.me().getPayTimeName((Integer)item.get("payTime")));
    	item.put("surplusTimeName", ConstantFactory.me().getSurplusTimeName((Integer)item.get("payTime"), (Date)item.get("startTime")));
    	model.addAttribute("item", item);
    	return PREFIX + "rtk_detail.html";
    }
    
    /**
     * 跳转到围栏修改页面
     */
    @RequestMapping(value = "/rtk/update_eleFence/{accountId}")
    public String updateEleFence(@PathVariable("accountId") Integer accountId,Model model) {
    	Map<String, Object> account = accountService.selectByAccountId(accountId);
    	model.addAttribute("account", account);
    	List<EleFence> eleFenceList = eleFenceService.selectList(new EntityWrapper<EleFence>());
    	model.addAttribute("eleFenceList", eleFenceList);
    	return PREFIX + "rtk_ele_fence.html";
    }
    
    
    /**
     * 修改围栏
     * @param account
     * @return
     */
    @RequestMapping(value = "/rtk/update/eleFence")
    @ResponseBody
    @Permission
    public Object updateEleFence(Account account) {
    	account.setUpdateTime(new Date());
    	boolean flag = accountService.updateById(account);
    	if(flag) {
    		EleFence eleFence = eleFenceService.selectById(account.getEleFenceId());
    		ConstantFactory.me().toSendUserMsg("USER_FENCE", "差分账号（“"+account.getAccount()+"”）的围栏范围已经变更为："+eleFence.getFenceName()+"，请注意查看！", account.getUserId());
    	}
        return SUCCESS_TIP;
    }
    
    
    
    /**
     * 跳转到日志页面
     */
    @RequestMapping("/account_log")
    public String rtdLog() {
        return PREFIX + "account_log.html";
    }
    
    /**
     * 获取账号日志
     */
    @RequestMapping(value = "/account_log/list")
    @ResponseBody
    @Permission
    public ResponseResult<Object> rtdLogList(@RequestParam(value="account", defaultValue="")String account, 
    		@RequestParam(value="logTime", defaultValue="")String logTime, 
    		@RequestParam(value="status", defaultValue="")String status) {
    	ResponseResult<Object> result = new ResponseResult<Object>();
    	Page<Object> page = new PageFactory<Object>().defaultPage();
    	//TODO 接口不通，使用临时数据
//    	String json = HttpUtils.get("http://49.4.94.172:9099/shxcors/account/log"
//    			+ "?pageSize=" + page.getSize()
//    			+ "&pageNum=" + page.getCurrent()
//    			+ "&login=" + account
//    			+ "&logTime=" + logTime
//    			+ "&status=" + status
//    			);
        String json = "{endRow:2,firstPage:1,hasNextPage:false,hasPreviousPage:false,isFirstPage:true,isLastPage:true,lastPage:1,list:[{login:\"SHY081/shy881001\",status:1,logTime:\"2019-05-28 11:05:15\"},{login:\"SHY001/shy081001\",status:8,logTime:\"2019-05-28 11:05:15\"},{login:\"SHY002/shy081002\",status:1,logTime:\"2019-05-28 14:56:33\"}],navigateFirstPage:1,navigateLastPage:1,navigatePages:8,navigatepageNums:[1],nextPage:0,pageNum:1,pageSize:3,pages:1,prePage:0,size:3,startRow:8}";
    	JSONObject jsonData = JSONObject.parseObject(json);
        result.setData(jsonData.get("list"));
        result.setCount((Integer)jsonData.get("size"));
     	result.setCode(SUCCESS_TIP.getCode());
     	result.setMsg(SUCCESS_TIP.getMessage());
 		return result;
    }
    
    
    /**
     * 跳转到实时位置页面
     */
    @RequestMapping("/locat")
    public String locat(Model model) {
    	List<Account> accountList = accountService.selectList(new EntityWrapper<Account>().eq("binding_state", 1).eq("flag", 1));
    	model.addAttribute("accountList", accountList);
        //TODO 接口不通，使用临时数据
    	//查询在线差分账号
//    	String json = HttpUtils.get("http://49.4.94.172:9099/shxcors/account/online");
    	String json = "[\"SHY001/shy001001\",\"5HY003/shy001003\",\"SHY002/shy001002\"]";

    	JSONArray jsonArray = JSONObject.parseArray(json);
    	List<String> onlineList = new ArrayList<String>();
    	if(jsonArray.size()>0){
  		  for(int i=0; i<jsonArray.size(); i++){
  			String account = jsonArray.getString(i);
  			onlineList.add(account);
  			
  		  }
  		}
    	model.addAttribute("onlineList", onlineList);
        return PREFIX + "account_locat.html";
    }
    
    
    /**
     * 根据差分账号查询设备位置
     * @param account
     * @return
     */
    @RequestMapping(value = "/locat/position")
    @ResponseBody
    public ResponseResult<Object> locatPosition(String account) {
    	ResponseResult<Object> result = new ResponseResult<Object>();
        //TODO 接口不通，使用临时数据
//    	String json = HttpUtils.get("http://49.4.94.172:9099/shxcors/account/position"
//    			+ "?account=" + account);
        String json = "{Latitude:33.123432,Longitude:188.342172}";
    	JSONObject jsonData = JSONObject.parseObject(json); 
    	if(ToolUtil.isEmpty(jsonData)) {
    		throw new SxbdException(400,"数据不存在");
    	}
        result.setData(jsonData);
     	result.setCode(SUCCESS_TIP.getCode());
     	result.setMsg(SUCCESS_TIP.getMessage());
 		return result;
    }
    
    
    /**
     * 获取所有账号的位置
     * @return
     */
    @RequestMapping(value = "/locat/allpositon")
    @ResponseBody
    public ResponseResult<Object> locatAllpositon() {
    	ResponseResult<Object> result = new ResponseResult<Object>();
        //TODO 接口不通，使用临时数据
//    	String json = HttpUtils.get("http://49.4.94.172:9099/shxcors/account/allpositon");
        String json = "{Longitude:109.12343,Latitude:35.432212,Login:\"SHY0001/shy000101\"},{Longitude:109.92343,Latitude:35.032212,Login:\"SHY0001/shy000102\"},{Longitude:109.92343,Latitude:35.032212,Login:\"SHY0002/shy000101}";
    	JSONArray jsonArray = JSONObject.parseArray(json);
    	if(ToolUtil.isEmpty(jsonArray)) {
    		throw new SxbdException(400,"数据不存在");
    	}
        result.setData(jsonArray);
     	result.setCode(SUCCESS_TIP.getCode());
     	result.setMsg(SUCCESS_TIP.getMessage());
 		return result;
    }
    
    
    /**
     * 跳转到历史轨迹页面
     * @param model
     * @return
     */
    @RequestMapping("/locus")
    public String locus(Model model) {
    	List<Account> accountList = accountService.selectList(new EntityWrapper<Account>().eq("binding_state", 1).eq("flag", 1));
    	model.addAttribute("accountList", accountList);
        return PREFIX + "account_locus.html";
    }
    
    
    @RequestMapping(value = "/locus/history")
    @ResponseBody
    public ResponseResult<Object> locusHistory(String account) {
    	ResponseResult<Object> result = new ResponseResult<Object>();
        //TODO 接口不通，使用临时数据
//    	String json = HttpUtils.get("http://49.4.94.172:9099/shxcors/account/posHistory"
//    			+ "?account=" + account);
    	String json = "[{Latitude:34,Height:701,Longitude:108},{Latitude:34.143251,Height:782,Longitude:108.778788},{Latitude:34.098764,Height:788,Longitude:108.123121}]";
    	JSONArray jsonArray = JSONObject.parseArray(json);
    	if(ToolUtil.isEmpty(jsonArray)) {
    		throw new SxbdException(400,"数据不存在");
    	}
    	
    	List<Map<String, Object>> list = new ArrayList<>();
    	if(jsonArray.size()>0){
			for(int i=0; i<jsonArray.size(); i++){
				Double data[] = new Double[2];
				JSONObject jsonData = JSONObject.parseObject(jsonArray.getString(i)); 
				data[0] = jsonData.getDouble("Longitude");
				data[1] = jsonData.getDouble("Latitude");
				Map<String, Object> map = new HashMap<>();
				map.put("coordinates", data);
				map.put("type", "Point");
				Map<String, Object> geometry = new HashMap<>();
		    	geometry.put("geometry", map);
		    	list.add(geometry);
			}
    	}

        result.setData(list);
     	result.setCode(SUCCESS_TIP.getCode());
     	result.setMsg(SUCCESS_TIP.getMessage());
 		return result;
    }

    /**
     * 跳转到zbzh 坐标系统转换服务
     */
    @RequestMapping("/zbzh")
    public String zbzh() {
        return PREFIX + "zbzh.html";
    }

    /**
     * 获取zbzh 坐标系统转换服务 列表
     */
    @RequestMapping(value = "/zbzh/list")
    @ResponseBody
    @Permission
    public ResponseResult<Object> zbzhList(Integer theState,String account,String userName,String startDate,String endDate) {
        ResponseResult<Object> result = new ResponseResult<Object>();
        Page<Account> page = new PageFactory<Account>().defaultPage();
        Map<String, Object> params = new HashMap<>(16);
        params.put("account", account);
        params.put("userName", userName);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("serviceType", SxbdConstants.SERVICE_TYPE_ZBZH.toUpperCase());

        List<Map<String, Object>> accounts = accountService.selectTaskAccounts(page, params);
        result.setData(new AccountWarpper(accounts).warp());
        result.setCount(page.getTotal());
        result.setCode(SUCCESS_TIP.getCode());
        result.setMsg(SUCCESS_TIP.getMessage());
        return result;
    }

    /**
     * 跳转到jzsj 基站数据服务
     */
    @RequestMapping("/jzsj")
    public String jzsj() {
        return PREFIX + "jzsj.html";
    }

    /**
     * 跳转到jzsj 基站数据服务 列表
     */
    @RequestMapping(value = "/jzsj/list")
    @ResponseBody
    @Permission
    public ResponseResult<Object> jzsjList(Integer theState,String account,String userName,String startDate,String endDate) {
        ResponseResult<Object> result = new ResponseResult<Object>();
        Page<Account> page = new PageFactory<Account>().defaultPage();
        Map<String, Object> params = new HashMap<>(16);
        params.put("account", account);
        params.put("userName", userName);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("serviceType", SxbdConstants.SERVICE_TYPE_JZSJ.toUpperCase());

        List<Map<String, Object>> accounts = accountService.selectTaskAccounts(page, params);
        result.setData(new AccountWarpper(accounts).warp());
        result.setCount(page.getTotal());
        result.setCode(SUCCESS_TIP.getCode());
        result.setMsg(SUCCESS_TIP.getMessage());
        return result;
    }

    /**
     * 基站数据任务 详情
     */
    @RequestMapping(value = "/jzsj/detail/{accountId}")
    public String jzsjDetail(@PathVariable("accountId") Integer accountId,Model model) {
        Map<String, Object> item = accountService.selectByAccountId(accountId);
        model.addAttribute("item", item);
        return PREFIX + "jzsj_detail.html";
    }

    /**
     * 坐标转换 详情
     */
    @RequestMapping(value = "/zbzh/detail/{accountId}")
    public String zbzhDetail(@PathVariable("accountId") Integer accountId,Model model) {
        Map<String, Object> item = accountService.selectByAccountId(accountId);
        String fileIds = item.get("fileIds").toString();
        //根据fileId 获取文件信息
        List<ZbzhFile> zbzhFiles = null;
        List<ZbzhFile> zVo = new ArrayList<>();
        if (ToolUtil.isNotEmpty(fileIds)) {
            String[] fileIdArr = fileIds.toString().split(",");
            zbzhFiles = zbzhFileService.selectBatchIds(Arrays.asList(fileIdArr));
            if (ToolUtil.isNotEmpty(zbzhFiles)) {
                for (ZbzhFile zbzhFile : zbzhFiles) {
                    if (!zbzhFile.getFileName().matches("(.*)\\.(shx|dbf|SHX|DBF)$")) {
                        zVo.add(zbzhFile);
                    }
                }
            }
            model.addAttribute("zbzhFiles", zVo);
        } else {
            throw new SxbdException("未获取到转换文件!");
        }
        model.addAttribute("item", item);
        return PREFIX + "zbzh_detail.html";
    }
}
